<template>
  <div class="container">
    <h2>注册</h2>
    <form @submit.prevent="handleRegister">
      <div class="form-group">
        <label for="registerEmail">邮箱:</label>
        <input type="text" id="registerEmail" v-model="register.email" required />
        <span v-if="emailExists" style="color: red;">邮箱已经被注册。</span>
      </div>
      <div class="form-group">
        <label for="registerPassword">密码:</label>
        <input type="password" id="registerPassword" v-model="register.password" required />
      </div>
      <div class="form-group">
        <label for="registerNickname">昵称:</label>
        <input type="text" id="registerNickname" v-model="register.nickname" required />
      </div>
      <button type="submit">注册</button>
    </form>
    <p>已经有账户？<router-link to="/login">登录</router-link></p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      register: {
        email: '',
        password: '',
        nickname: ''
      },
      emailExists: false // 用于指示邮箱是否已被注册
    };
  },
  methods: {
    checkEmailExists() {
      // 检查邮箱是否已存在
      return axios.get(`http://localhost:9090/student/check-email/${this.register.email}`)
          .then(response => {
            this.emailExists = response.data.exists;
          });
    },
    handleRegister() {
      this.checkEmailExists().then(() => {
        if (this.emailExists) {
          alert('邮箱已经被注册，请使用其他邮箱！');
          return;
        }

        const registerData = {
          email: this.register.email,
          password: this.register.password,
          nickname: this.register.nickname
        };
        axios.post('http://localhost:9090/student/register', registerData)
            .then(response => {
              console.log("注册成功", response);
              localStorage.setItem('user', JSON.stringify(response.data));
              this.$router.push('/');
            })
            .catch(error => {
              console.error("注册失败", error);
            });
      });
    }
  }
};
</script>

<style scoped>
.container {
  max-width: 300px;
  margin: auto;
  background: #fff;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
h2 {
  text-align: center;
}
.form-group {
  margin-bottom: 15px;
}
input[type="text"], input[type="password"] {
  width: 100%;
  padding: 10px;
  margin: 5px 0;
  border: 1px solid #ccc;
  border-radius: 5px;
}
button {
  width: 100%;
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
button:hover {
  background-color: #0056b3;
}
</style>
